import { useState, useRef, useEffect } from 'react';
import { Button, Divider } from 'antd';
import { Flipper, Flipped } from 'react-flip-toolkit';
import { DragStyle, FlipStyle } from './style';
// import { shuffle } from 'lodash-es';

const FlipToolkit = () => {
	const [list, setList] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
	const boxRef = useRef<HTMLDivElement>();
	const sourceNode = useRef<HTMLDivElement>();

	// const [, setUpdate] = useState({});

	const ondragenter = (e: DragEvent) => {
		e.stopPropagation();
		e.preventDefault();
		if (e.target === boxRef.current || e.target === sourceNode.current) return;
		console.log('ondragenter');
		const children = Array.from(boxRef.current.children);
		const sourceIndex = children.indexOf(sourceNode.current as Element);
		const targetIndex = children.indexOf(e.target as Element);
		const newList = [...list];
		newList.splice(targetIndex, 0, newList.splice(sourceIndex, 1)[0]);
		setList(newList);
	};

	function foo() {
		boxRef.current.ondragstart = (e) => {
			e.stopPropagation();
			setTimeout(() => {
				(e.target as HTMLDivElement).classList.add('moving');
			}, 0);
			sourceNode.current = e.target as HTMLDivElement;
			e.dataTransfer.effectAllowed = 'move';
		};

		boxRef.current.ondragover = (e) => {
			e.stopPropagation();
			e.preventDefault();
		};

		boxRef.current.ondragenter = ondragenter;

		boxRef.current.ondragend = (e) => {
			(e.target as HTMLDivElement).classList.remove('moving');
		};
	}

	useEffect(() => {
		foo();
	}, [list]);

	return (
		<FlipStyle>
			<Button
				type="primary"
				onClick={() => {
					// console.log(data.join(''));
					const length = list.length;
					const arr = [...list];
					arr.unshift(length + 1);
					setList(arr);
					// setData(shuffle(data));
				}}
			>
				push
			</Button>
			<Divider />
			<Flipper flipKey={list.join('')} spring={{ stiffness: 350 }}>
				<DragStyle>
					<div ref={boxRef} className="drag-box">
						{list.map((it) => (
							<Flipped key={it} flipId={it}>
								<div className="item" draggable>
									{it}
								</div>
							</Flipped>
						))}
					</div>
				</DragStyle>

				{/* <div className="box">
					{data.map((d) => (
						<Flipped key={d} flipId={d}>
							<div className="item">{d}</div>
						</Flipped>
					))}
				</div> */}

				{/* <Flipped flipId="square">
					<div
						className={fullScreen ? 'full-screen-square' : 'square'}
						onClick={toggleFullScreen}
					/>
				</Flipped> */}
			</Flipper>
		</FlipStyle>
	);
};

export default FlipToolkit;
